<script setup>
import {sendPhoneCodeRegisterService, userRegisterByGiteeService} from '@/api/user.js'
import {useRoute} from "vue-router";
import {reactive, ref} from "vue";
import router from "@/router";
import {ElMessage} from "element-plus";
import {Cellphone, Key, User} from "@element-plus/icons-vue";
// const router = useRouter();
// var url = window.location.href ;//获取当前url
//
// var cs_arr = url.split('#')[0].split('?')[1].split('&');//参数字符串分割为数组
// var cs={};
// for(var i=0;i<cs_arr.length;i++){//遍历数组，拿到json对象
//   cs[cs_arr[i].split('=')[0]] = cs_arr[i].split('=')[1]
// }

const route=useRoute()
const code=reactive(route.query.code);
// let code = cs.code;
console.log(code)
const giteeRegisterData = ref({
  username:'',
  phoneNumber:'',
  phoneCode:'',
  code:code
})
const registerByGitee = async ()=>{
  // let result = await isGitee(code);
  // if(result.status === 1){
  //   console.log(result.data)
  //   // localStorage.setItem("token", result.data.token);
  //   ElMessage.error(result.message);
  //   await router.go(-1);
  // }else{
    // alert("error");
    // await router.push('/login');
    let result1 = await userRegisterByGiteeService(giteeRegisterData.value);
    if(result1.status === 1){
      console.log(result1.data)
      // localStorage.setItem("token", result1.data.token);
      // localStorage.setItem("username", result1.data.username);
      ElMessage.success(result1.message);
      router.push('/login');
    }else {
      ElMessage.error(result1.message);
      await router.go(0);
    }
  // }
}
// registerByGitee();
//绑定
//判断用户名是否存在
const checkUsernameExists = (rule, value, callback) => {
  return new Promise((resolve) => {
    fetch(`http://localhost:8080/users/username/${value}`)
        .then(response => {
          if (!response.ok) {
            callback(new Error('网络响应失败'));
          }
          return response.json();
        })
        .then(data => {
          if (data.status === 1) {
            callback(new Error('用户名已存在，请更换用户名！'));
            resolve(false);
          } else {
            callback();
            resolve(true);
          }
        })
        .catch(error => {
          console.log(error)
          // callback(error);
          // reject(error);
        });
  });
};
//判断手机号是否存在
const checkPhoneNumberExists = (rule, value, callback) => {
  return new Promise((resolve) => {
    fetch(`http://localhost:8080/users/phone/${value}`)
        .then(response => {
          if (!response.ok) {
            callback(new Error('网络响应失败'));
          }
          return response.json();
        })
        .then(data => {
          if (data.status === 1) {
            callback(new Error('手机号已存在，请更换手机号！'));
            resolve(false);
          } else {
            callback();
            resolve(true);
          }
        })
        .catch(error => {
          console.log(error)
          // callback(error);
          // reject(error);
        });
  });
};
const rules = {
  username:[
    {required: true, message:'请输入用户名',trigger:'blur'},
    {min:1,max:20,message: '请输入长度为1-20位非空字符',trigger: 'blur'},
    { validator: checkUsernameExists, trigger: 'blur'}
  ],
  phoneNumber:[
    {required: true, message:'请输入手机号',trigger:'blur'},
    {required: true, max:11,pattern: /^1[3456789]\d{9}$/, message: '手机号格式不正确',trigger: 'blur'},
    {validator: checkPhoneNumberExists, trigger: 'blur'}
  ],
  phoneCode:[
    {required: true, message:'请输入验证码',trigger:'blur'}
  ],
}
//发送注册验证码
const sendPhoneCodeRegister = async (phoneNumber)=>{
  let result = await sendPhoneCodeRegisterService(phoneNumber);
  if(result.status === 1){
    ElMessage.success(result.message);
  }else{
    ElMessage.error(result.message);
  }
}
</script>
<template>
  <el-main>
    <div class="center-wrapper" style="margin-top: 3%">
      <el-card>
        <el-form ref="form" label-width="auto" style="max-width: 600px" :model="giteeRegisterData" :rules="rules">
          <el-form-item style="text-align: center">
            <h3 style="text-align: center; margin: 0 auto;font-size: 20px">绑定用户信息</h3>
          </el-form-item>
          <el-form-item prop="username">
            <el-input :prefix-icon="User" placeholder="请输入用户名" size="large" style="width: 350px" v-model="giteeRegisterData.username"/>
          </el-form-item>
          <el-form-item prop="phoneNumber">
            <el-input :prefix-icon="Cellphone" placeholder="请输入手机号" style="width: 350px" size="large" v-model="giteeRegisterData.phoneNumber"/>
          </el-form-item>
          <el-form-item prop="phoneCode">
            <el-input :prefix-icon="Key" placeholder="请输入验证码" size="large" v-model="giteeRegisterData.phoneCode">
              <template #append>
                <el-button @click="sendPhoneCodeRegister(giteeRegisterData.phoneNumber)" style="max-width: 100px;">获取验证码</el-button>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item>
            <el-button class="button" type="primary" style="width: 100%;font-size: 18px;border-radius: 10px" size="large" @click="registerByGitee()">绑定</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>
  </el-main>
</template>
